package com.chenxin.interact.handler.mesHandler;

import com.chenxin.common.utils.StringUtils;
import com.chenxin.interact.domain.MesValue.MesQualityValue;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.mesNotice.QualityNoticeDTO;
import com.chenxin.interact.domain.mesRequest.WmsQualityReqDTO;
import com.chenxin.interact.domain.mesResponse.MesResponseDTO;
import com.chenxin.interact.domain.mesResult.MesContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class MesQualityHandler {
    public void notice(UrlMap urlMap, List<QualityNoticeDTO> qualitys, String method) {
        // 判定相关信息是否为空
        if (urlMap == null || qualitys == null || StringUtils.isEmpty(method)) {
            log.info("参数信息不能为空");
            return;
        }
        List<MesQualityValue> values = new ArrayList<>();
        // 构建请求实体类（订单）
        MesQualityValue value = new MesQualityValue();
        value.setValue(qualitys);
        values.add(value);

        MesContext mesContext = new MesContext();
        mesContext.setTicket(urlMap.getToken());

        WmsQualityReqDTO qualityReq = new WmsQualityReqDTO();
        qualityReq.setApiType("QMSInteractiveController");
        qualityReq.setMethod(method);
        qualityReq.setParameters(values);
        qualityReq.setContext(mesContext);

        // 记录请求信息用于调试
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String reqJson = objectMapper.writeValueAsString(qualityReq);
            log.info("MES请求参数为：{}", reqJson);
        } catch (JsonProcessingException e) {
            log.error("序列化请求参数时出错: ", e);
        }

        // 构建WebClient（token信息由参数携带）
        WebClient client = WebClient.builder().baseUrl(urlMap.getUrlAdr())
                .defaultHeader("Content-Type", "application/json")
                .build();

        // 2.发送POST请求
        try {
            MesResponseDTO response = client.post()
                    .uri(urlMap.getUriAdr())
                    .bodyValue(qualityReq)
                    .retrieve()
                    .bodyToMono(MesResponseDTO.class)
                    .block();
            // 3.将接收到的物料信息写入数据库
            assert response != null;
            log.info("MES返回的token信息为：{}", response);
        } catch (WebClientResponseException.BadRequest e) {
            log.error("发送到MES的请求返回400错误，状态码: {}, 响应内容: {}",
                    e.getRawStatusCode(), e.getResponseBodyAsString());
            throw e;
        } catch (Exception e) {
            log.error("发送到MES的请求时发生未知错误: ", e);
            throw e;
        }
    }
}
